package com.hr.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 *  用户
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements UserDetails
{
    @Id
    private int id;
    private String account;
    private String password;
    private String identity;

    private Archive archive=null;



    @Override
    public Collection<? extends GrantedAuthority> getAuthorities()
    {
        List<SimpleGrantedAuthority> privileges = new ArrayList<>();
        if(archive==null)
            return privileges;
        for(Position position: archive.getPositions())
        {
            if(position.getEnd()==null&&position.getPrivilege()!=null)
            {
                privileges.add(new SimpleGrantedAuthority(position.getCompany().getId()+"_"+position.getPrivilege())); //权限的形式为 ”公司id“+“_”+“权限等级”
            }
        }
        return privileges;
    }

    @Override public String getUsername()
    { return account; }

    @Override public boolean isAccountNonExpired()
    { return true; }

    @Override public boolean isAccountNonLocked()
    { return true; }

    @Override public boolean isCredentialsNonExpired()
    { return true; }

    @Override public boolean isEnabled()
    { return true; }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return Objects.equals(account, user.account);
    }

    @Override
    public int hashCode() {
        return Objects.hash(account);
    }
}
